//
//  LoginViewController.m
//  金融
//
//  Created by Apple on 2018/1/29.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "LoginViewController.h"
#import "ForgetViewController.h"
//#import <CloudPushSDK/CloudPushSDK.h>

@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIButton     * regest;
@property (nonatomic, strong) UIButton     * loginBtn;
@end

@implementation LoginViewController

- (UIButton *)regest
{
    if (!_regest) {
        _regest = [UIButton new];
        [_regest setTitle:@"注册" forState:UIControlStateNormal];
        [_regest setTitleColor:SELECTCOLOR forState:UIControlStateNormal];
        _regest.titleLabel.font = FONT(15);
        [_regest addTarget:self action:@selector(clickRegester) forControlEvents:UIControlEventTouchUpInside];
    }
    return _regest;
}

- (UIButton *)msgBtn
{
    if (!_msgBtn) {
        _msgBtn = [UIButton new];
        [_msgBtn setTitle:@"短信登录" forState:UIControlStateNormal];
        [_msgBtn setTitleColor:UIColorRGB(0x2772ff) forState:UIControlStateNormal];
        _msgBtn.titleLabel.font = FONT(15);
        [_msgBtn addTarget:self action:@selector(clickForgetLogin) forControlEvents:UIControlEventTouchUpInside];
    }
    return _msgBtn;
}

- (UIButton *)loginBtn
{
    if (!_loginBtn) {
        _loginBtn = [UIButton new];
        [_loginBtn setTitle:@"立即登录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginBtn setBackgroundColor:UIColorRGB(0x2772ff)];
        _loginBtn.titleLabel.font = FONT(17);
        _loginBtn.layer.cornerRadius = 5.f;
        _loginBtn.layer.masksToBounds = YES;
        [_loginBtn addTarget:self action:@selector(clickLogin) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

- (UITextField *)phoneTF
{
    if (!_phoneTF) {
        _phoneTF = [UITextField new];
        _phoneTF.placeholder = @"手机号";
        _phoneTF.font = FONT(15);
    }
    return _phoneTF;
}
- (UITextField *)passTF
{
    if (!_passTF) {
        _passTF = [UITextField new];
        _passTF.placeholder = @"密码";
        _passTF.font = FONT(15);
    }
    return _passTF;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBar];
    [self setCusView];
}
- (void)setNavBar
{
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = @"账号登录";
    [self.barView addSubview:self.regest];
    [self.regest mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.barView.mas_right).offset(-25);
        make.height.mas_offset(44);
        make.width.mas_offset(60);
        make.centerY.mas_equalTo(self.barView);
    }];
    self.regest.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
}
- (void)setCusView
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.phoneTF];
    [self.view addSubview:self.passTF];
    [self.view addSubview:self.loginBtn];
    [self.view addSubview:self.msgBtn];
    UILabel * phoneL = [UILabel new];
    [self.view addSubview:phoneL];
    phoneL.backgroundColor = UIColorRGB(0x929292);
    
    UILabel * passL = [UILabel new];
    [self.view addSubview:passL];
    passL.backgroundColor = UIColorRGB(0x929292);
    
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.barView.mas_bottom).offset(64);
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.height.mas_equalTo(40);
    }];
    [phoneL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.phoneTF.mas_bottom);
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.height.mas_equalTo(0.5);
    }];
    [self.passTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(phoneL.mas_bottom).offset(15);
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.height.mas_equalTo(40);
    }];
    [passL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.passTF.mas_bottom);
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.height.mas_equalTo(0.5);
    }];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(passL.mas_bottom).offset(60);
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.height.mas_equalTo(40);
    }];
    [self.msgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.loginBtn.mas_bottom).offset(25);
        make.width.mas_greaterThanOrEqualTo(30);
        make.right.mas_equalTo(-25);
        make.height.mas_equalTo(30);
    }];
    self.phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.phoneTF.delegate = self;
    self.passTF.delegate = self;
    self.passTF.keyboardType = UIKeyboardTypeASCIICapable;
    self.passTF.returnKeyType = UIReturnKeyDone;
    self.passTF.secureTextEntry = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickTap)];
    [self.view addGestureRecognizer:tap];
    
    
    NSMutableAttributedString* tncString = [[NSMutableAttributedString alloc] initWithString:self.msgBtn.titleLabel.text];
    
    [tncString addAttribute:NSUnderlineStyleAttributeName
                      value:@(NSUnderlineStyleSingle)
                      range:(NSRange){0,[tncString length]}];
    //此时如果设置字体颜色要这样
    //    [tncString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[tncString length])];
    
    //设置下划线颜色...
    [tncString addAttribute:NSUnderlineColorAttributeName value:TITLEColor range:(NSRange){0,[tncString length]}];
    [self.msgBtn setAttributedTitle:tncString forState:UIControlStateNormal];
}
- (void)clickTap
{
    [self.phoneTF resignFirstResponder];
    [self.passTF resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.phoneTF) {
        [self.passTF becomeFirstResponder];
    }else{
        [self clickLogin];
        [textField resignFirstResponder];
    }
    return YES;
}
- (void)clickBackAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


- (void)clickRegester {
    RegisterViewController *rc = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:rc animated:YES];
}

- (void)clickForgetLogin {
    ForgetViewController * fv = [[ForgetViewController alloc] init];
    WeakSelf
    fv.myClass = self.myClass;
    fv.clickForgetBlock = ^{
        if (weakSelf.LoginSuccessBlock) {
            weakSelf.LoginSuccessBlock();
        }
    };
    [self.navigationController pushViewController:fv animated:YES];
}
- (void)clickLogin{
    
    if (self.phoneTF.text.length == 0 || self.passTF.text.length == 0) {
        return;
    }
//    NSDictionary * dict = @{@"username":self.phoneTF.text,@"password":self.passTF.text,@"extraParams":@{@"deviceId":[CloudPushSDK getDeviceId]}};
//    WeakSelf
//    [HttpRequest postWithURLString:HOST(@"auth/login") parameters:dict showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
//        [MyObject failedPrompt1:responseObject[@"message"]];
//        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
//            [HFUser saveToken:responseObject[@"data"][@"token"]];
//            [HFUser rememberUserID:responseObject[@"data"][@"userId"]];
//            [HFUser saveRefreshToken:responseObject[@"data"][@"refreshToken"]];
//            [HFUser rememberUsername:responseObject[@"data"][@"username"]];
//            [HFUser rememberNickName:responseObject[@"data"][@"nickName"]];
//            [weakSelf saveIcon:responseObject[@"data"][@"avatar"]];
//            [[NSNotificationCenter defaultCenter] postNotificationName:LOGINSUCCESS object:nil];
//        }
//    } failure:^(NSError * _Nullable error) {
//        NSLog(@"%@",error);
//    }login:^(BOOL isLogin) {
//        
//    }];
}

- (void)saveIcon:(NSString *)image
{
    WeakSelf
    dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL); // 创建GCD线程队列
    dispatch_async(xrQueue, ^{
        // 异步下载图片
        UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:image]]];
        // 主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *path_document = NSHomeDirectory();
            //设置一个图片的存储路径
            NSString *imagePath = [path_document stringByAppendingString:@"/Documents/icon.png"];
            //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
            [UIImagePNGRepresentation(img) writeToFile:imagePath atomically:YES];
            if (weakSelf.LoginSuccessBlock) {
                weakSelf.LoginSuccessBlock();
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
    });
}

@end

